//
//  AppenSelectViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/9/20.
//

#import "AppenSelectViewController.h"
#import "AddPondModel.h"

@interface AppenSelectViewController ()
@property (nonatomic ,strong) NSMutableArray <PositionsModel *>* modelArray;
@property (nonatomic ,strong) NSMutableArray <PositionsModel *>* AllModelArray;
@property (nonatomic ,strong)  UIButton * textRemovebtn;
@property (nonatomic ,strong)  UITextField * textField ;
@end

@implementation AppenSelectViewController
-(NSMutableArray<PositionsModel *> *)AllModelArray{
    if(!_AllModelArray){
        _AllModelArray = [NSMutableArray array];
    }
    return _AllModelArray;
}

- (NSMutableArray<PositionsModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray arrayWithArray:self.AllModelArray];
    }
    return _modelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.StatusBarColor = NO;
    self.view.backgroundColor = KcolorHex(@"#FBFBFB");
    
    UIView * topview = [UIView new];
    topview.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    
  
    
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(120));
    }];
    
    
    
    UIImageView * leftimg = kimageView(@"left_black_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    UILabel * leftlab = [DTKTool labelWithText:@"选择养殖场" andFont:kCFont(18) andTextColor:KcolorHex(@"#333333")];
    [topview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.centerY.offset(KTop/2);
    }];
    
    UIView * ssview = [UIView new];
    ssview.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:ssview];
    [ssview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);

        make.top.equalTo(topview.mas_bottom);
        make.height.offset(kwt(56));
    }];
    
    UIView * btnview = [UIView new];
    [DTKTool YJBK:kwt(5) andView:btnview andWidth:1 andColor:KcolorHex(@"#D4D5DA")];
    [ssview addSubview:btnview];
    [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(10));
        make.right.offset(kwt(-10));
        make.top.offset(kwt(11));
        make.height.offset(kwt(40));
    }];
    
    UIImageView * btnviewimg = kimageView(@"program_search");
    [btnview addSubview:btnviewimg];
    [btnviewimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.centerY.offset(0);
        make.height.width.offset(kwt(16));
    }];
    
    UITextField * textField = [UITextField new];
    self.textField = textField;
    textField.backgroundColor = UIColor.whiteColor;
    textField.attributedPlaceholder = [DTKTool AttributedStringWithStr:@"请输入养殖场名称" andNodeColor:KcolorHex(@"#89908D") andSeledColor:KcolorHex(@"#89908D") andFont:kFont(16) andPattenr:@""];
    textField.font = kFont(16);
    textField.textColor = KcolorHex(@"#222222");
    [btnview addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(40));
        make.right.offset(kwt(-130));
        make.centerY.offset(0);
        make.height.offset(kwt(23));
    }];
    [textField addTarget:self action:@selector(textFieldDidChangeValue:)  forControlEvents:UIControlEventEditingChanged];
    
    UIButton * textRemovebtn = [UIButton buttonWithType:0];
    self.textRemovebtn = textRemovebtn;
    textRemovebtn.hidden = YES;
    textRemovebtn.addTarget(self,@selector(textRemovebtnClick));
    [textRemovebtn setImage:[UIImage imageNamed:@"search_delete"] forState:UIControlStateNormal];
    [btnview addSubview:textRemovebtn];
    [textRemovebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kwt(23));
        make.right.offset(kwt(-90));
        make.centerY.offset(0);
    }];
    
    
    UIView * btnline = [UIView new];
    btnline.backgroundColor = KcolorHex(@"#EAEBED");
    [btnview addSubview:btnline];
    [btnline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(280));
        make.centerY.offset(0);
        make.width.offset(0.5);
        make.height.offset(kwt(28));
    }];
    
    UILabel * btnviewsslab = [DTKTool labelWithText:@"搜索" andFont:kCFont(16) andTextColor:KcolorHex(@"#0063FC")];
    [btnview addSubview:btnviewsslab];
    [btnviewsslab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-16));
        make.centerY.offset(0);
    }];
    
   
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#FBFBFB");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(ssview.mas_bottom);
    }];
    
    [self loadNewData];
    
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{ return YES; }
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.textField.text.length < 1){
        return  [UIView new];
    }
    //加入你自定义的view
    UIView * noView = [UIView new];
    UIView * NewnoView = [UIView new];
//    NewnoView.backgroundColor = UIColor.whiteColor;
    [noView addSubview:NewnoView];
    [NewnoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(KSCREEN_WIDTH);
        make.center.offset(0);
        make.height.mas_offset(KSCREEN_HEIGHT);
    }];
    UIImageView * noImage = [UIImageView new];
    [noView addSubview:noImage];
    noImage.image = [UIImage imageNamed:@"no_search"];
    [noImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(-100);
    }];
    
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    noTitleLab.text = @"暂无搜索记录\n换个关键词试试~";
    noTitleLab.numberOfLines = 2;
    noTitleLab.font = kFont(16);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#262626"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(noImage.mas_bottom).offset(30);
        make.centerX.mas_offset(0);
    }];
    
    return noView;
}

- (void)textRemovebtnClick{
    self.textField.text = @"";
    self.textRemovebtn.hidden = YES;
    [self.modelArray removeAllObjects];
    [self.tableview reloadData];
}

- (void)textFieldDidChangeValue:(UITextField *)sender{
    if(sender.markedTextRange == nil){
        NSLog(@"%@",sender.text);
        if(sender.text.length > 0){
            [self.modelArray removeAllObjects];
            for (PositionsModel * model in self.AllModelArray) {
                if([model.value containsString:sender.text] || [model.label containsString:sender.text]){
                    [self.modelArray addObject:model];
                }
            }
        } else {
            self.modelArray = [NSMutableArray arrayWithArray:self.AllModelArray];
        }
        [self.tableview reloadData];
    }
    self.textRemovebtn.hidden = (sender.text.length == 0);

}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
 }
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return kwt(55);
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MJWeakSelf
    AppenSelectTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AppenSelectTableViewCell"];
    if (cell == nil) {
        cell = [[AppenSelectTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AppenSelectTableViewCell"];
    }
    cell.model = self.modelArray[indexPath.row];
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell ;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self QHTKwithID:self.modelArray[indexPath.row].value];
}


- (void)loadNewData{
    [self.view showBusyHUD];
    [SCNetManger PostsysDepartQueryTreeBreedFarmWithDict:[NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];

        if(model.code ==200){
            self.AllModelArray = [NSMutableArray arrayWithArray:[NSArray yy_modelArrayWithClass:PositionsModel.class json:model.result]];
            self.modelArray = [NSMutableArray arrayWithArray:self.AllModelArray];

            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)QHTKwithID:(NSString *)ID{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:ID forKey:@"appOrgCode"];
    [dict setObject:[UserInfoModel shared].userID forKey:@"id"];
    [SCNetManger PostappSelectAppDepartsWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            UserInfoDeModel * usermodel = [UserInfoDeModel yy_modelWithJSON:[model.result objectForKey:@"userInfo"]];
            [UserInfoModel shared].OrgCode = usermodel.appOrgCode;
            [self.view showWarning:@"切换成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];
//                NSString *accountPath = [documentPath stringByAppendingPathComponent:@"AppendFishpondViewController"];
//                [NSKeyedArchiver archiveRootObject:[AddPondModel new] toFile:accountPath];
//             
//                NSString *maccountPath = [documentPath stringByAppendingPathComponent:@"AppendMultipleFishpondViewController"];
//                [NSKeyedArchiver archiveRootObject:[AddPondModel new] toFile:maccountPath];
                
                // 2秒后执行的代码
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            [self.view showWarning:model.message];
        }
    }];}
@end



@implementation BreedFarmModel
@end
@interface AppenSelectTableViewCell ()
@property (nonatomic ,strong) UILabel * nameLab;
@property (nonatomic ,strong) UIImageView * seledimg;
@end

@implementation AppenSelectTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [self setupView];
    }
    return self;
}


- (void)setupView{
    
    self.backgroundColor = UIColor.clearColor;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.userInteractionEnabled = YES;
    self.contentView.userInteractionEnabled = YES;
    self.contentView.clipsToBounds = YES;
    
    UILabel * nameLab = [DTKTool labelWithText:@"-" andFont:kFont(18) andTextColor:KcolorHex(@"#222222")];
    [self.contentView addSubview:nameLab];
    self.nameLab = nameLab;
    [nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.centerY.offset(0);
    }];
    
    UIImageView * seledimg = kimageView(@"tangkou_determine");
    self.seledimg = seledimg;
    seledimg.hidden = YES;
    [self.contentView addSubview:seledimg];
    [seledimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-24));
        make.centerY.offset(0);
        make.width.height.offset(kwt(18));
    }];
    
    UIView * line = [UIView new];
    line.backgroundColor = KcolorHex(@"#E4E4E4");
    [self.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-12));
        make.left.offset(kwt(12));
        make.bottom.offset(0);
        make.height.offset(0.5);
    }];
}
- (void)setModel:(PositionsModel *)model{
    _model = model;
    if([[UserInfoModel shared].OrgCode isEqualToString:model.value]){
        self.nameLab.textColor = KcolorHex(@"#0063FC");
        self.nameLab.font = kCFont(18);
        self.seledimg.hidden = NO;
    } else {
        self.nameLab.textColor = KcolorHex(@"#222222");
        self.nameLab.font = kFont(18);
        self.seledimg.hidden = YES;
    }
    self.nameLab.text = model.label;
}
@end
